package com.crm.dao;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Transaction;

import com.crm.dao.base.BaseHibernateDAO;
import com.crm.po.Customer;

public class CustomerDAO extends BaseHibernateDAO {

	private static Logger logger = Logger.getLogger(CustomerDAO.class);
	
	public void save(Customer customer) {
		if(customer.getCid() == null || customer.getCid().trim().length() == 0){
			customer.setCid(this.getUUID());
		}
		Transaction transaction = getSession().beginTransaction();
		try {						
			this.getSession().save(customer);
			transaction.commit();
		} catch (RuntimeException e) {
			transaction.rollback();
			logger.error(e);
		} finally {
			this.closeSession();	
		}
	}

	public void saveOrUpdate(Customer customer) {
		if(customer.getCid() == null || customer.getCid().trim().length() == 0){
			customer.setCid(this.getUUID());
		}
		Transaction transaction = getSession().beginTransaction();
		try {						
			this.getSession().saveOrUpdate(customer);
			transaction.commit();
		} catch (RuntimeException e) {
			transaction.rollback();
			logger.error(e);
		} finally {
			this.closeSession();	
		}
	}
	
	public void delete(Customer customer) {
		Transaction transaction = getSession().beginTransaction();
		try {
			this.getSession().delete(customer);
			transaction.commit();
		} catch (RuntimeException e) {
			transaction.rollback();
			logger.error(e);
		} finally {
			this.closeSession();	
		}
	}

	public Customer findById(String id) {
		Customer customer = null;
		try {			
			customer = (Customer) this.getSession().get(Customer.class, id);
		} catch (RuntimeException e) {
			logger.error(e);
		} finally {
			this.closeSession();	
		}
		return customer;
	}
	
	@SuppressWarnings("unchecked")
	public List<Customer> customerList(String hql) {
		return (List<Customer>) findList(hql);
	}
	
	@SuppressWarnings("unchecked")
	public List<Customer> customerListPage(String hql, int start, int limit) {
		return (List<Customer>) findListPage(hql, start, limit);
	}

}